# -*- coding: utf-8  -*-
#    Adding Book Bot - A Python bot that uses Pywikipediabot framework and works on MediaWiki wikis at general.
#    Copyright (C) 2009 OsamaK
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    Please report bugs or help imporving this program by connecting to <OsamaK.WFM@gmail.com>
import wikipedia
import time, codecs
from okbot import *
footer, categories, book, author, pagecontect = (u"",u"",u"",u"", u"")
pages = {}
output = {}

#site = wikipedia.getSite(fam='wikisource',code='ar') # although it can be used directly on other wikis, but this is the default.
site = wikipedia.getSite()
def putbook():
  for pagesnum in range(len(pages.keys())):
      globals()['pagecontect'] = ""
      if pagesnum == 0:
        prevpage = ""
      else:
        prevpage = pages.keys()[pagesnum - 1]
      if pagesnum == (len(pages.keys()) - 1):
        nextpage = ""
      else:
        nextpage = pages.keys()[pagesnum + 1]
      page = book + "/" + pages.keys()[pagesnum]
      header = u"{{تروسية\n|عنوان = %s\n|مؤلف = %s\n|سابق = {{subst:#ifeq:[[%s/%s]]|[[%s/]]||[[%s/%s]]}}\n|تالي = {{subst:#ifeq:[[%s/%s]]|[[%s/]]||[[%s/%s]]}}\n}}" % (pages.keys()[pagesnum], author, book, prevpage, book, book, prevpage, book, nextpage, book, book, nextpage)

      pageOpject = wikipedia.Page(site,page)
      for line in pages.values()[pagesnum]:
        globals()['pagecontect'] += line
      pageOpject.put(header + '\n' + pagecontect + "\n" + footer + "\n" + categories)
    

def readbook():
  tmppagename = ""
  bookfile = codecs.open('/home/osama/TestBook','r','utf-8')
  lines = bookfile.readlines()
  for line in lines:
    # "Meta" info.
    if line.startswith(u"الهامش:"):
      globals()['footer'] += "\n" + line.strip(u"الهامش:")
      globals()['footer'] =  globals()['footer'].strip('\n').strip()
    elif line.startswith(u"الكتاب:"):
      globals()['book'] = line.strip(u"الكتاب:").strip().strip("\n")
    elif line.startswith(u"المؤلف:"):
      globals()['author'] = line.strip(u"المؤلف:").strip().strip("\n")
    elif line.startswith(u"التصانيف:"):
      tmpcategories = line.strip(u"التصانيف:").strip().split(u"،")
      for category in tmpcategories:
        globals()['categories'] = (globals()['categories'] + "\n" + u"[[تصنيف:" + category.strip() + "]]").rstrip("\n")
    # "Pages" info.
    elif line.startswith("==") and line.endswith("==\n"):
      tmppagename = line.lstrip("==").rstrip("==\n").strip()
      pages[tmppagename] = []
    else:
      try:
        pages[tmppagename].append(line)
      except KeyError:
        if not line.strip("\n").strip() == "":
          print "You have a line which is not under \"==\" and it doesn't start with a key word."

  outputfile = codecs.open('/home/osama/OutPutTest','w','utf-8')
  for lines in pages.items():
    outputfile.write( "\"" + lines[0] + "\"" + "\n")
    for line in lines[1]:
      outputfile.write(line)

if __name__ == '__main__':
  try:    readbook()
    putbook()
  finally:
    wikipedia.stopme()
